from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from backend.biz import BuyOrderBiz


# Create your views here.


class BuyOrderView(APIView):
    def post(self, request, *args, **kwargs):
        data = request.data
        if data.get('supplier') is None:
            data['supplier'] = 0

        ret = BuyOrderBiz().create(data)
        return Response(ret, status=status.HTTP_201_CREATED)

    def get(self, request, *args, **kwargs):
        ret = BuyOrderBiz().list()
        return Response(ret, status=status.HTTP_200_OK)


class BuyOrderInstanceView(APIView):
    def get(self, request, pk):
        try:
            ret = BuyOrderBiz().retrieve(pk)
            code = status.HTTP_200_OK
        except ValueError as e:
            ret = {'detail': str(e)}
            code = status.HTTP_400_BAD_REQUEST

        return Response(ret, status=code)

    def delete(self, request, pk):
        try:
            BuyOrderBiz().destroy(pk)
            return Response(status=status.HTTP_204_NO_CONTENT)
        except ValueError as e:
            return Response({'detail': str(e)}, status=status.HTTP_400_BAD_REQUEST)
